import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:native_dart_package/widget/yt_button.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/debounce_utils.dart';

///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2024年05月20日 08:51
class ChooseDevicePage extends StatefulWidget {
  final String title;
  final String listUrl;
  final Map<String, dynamic>? params;
  final String keyId;
  final String showName;
  final String searchKey;
  final String searchPlaceholder;
  final bool isRefresh;
  final List<int>? selectedIds;
  final bool isMultiSelect;//是否是多选 默认多选
  final Function(List, List<int>) selectedCompleted;

  const ChooseDevicePage(
      {required this.title,
      required this.listUrl,
      required this.params,
      required this.selectedCompleted,
      this.keyId = 'deviceId',
      this.showName = 'deviceName',
      this.searchKey = 'deviceName',
      required this.searchPlaceholder,
      this.selectedIds,
      this.isRefresh = true,
      this.isMultiSelect = true,
      super.key});

  @override
  State<ChooseDevicePage> createState() => _ChooseDevicePageState();
}

class _ChooseDevicePageState extends State<ChooseDevicePage> {
  String searchName = '';
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  List<dynamic> dataList = [];
  List<dynamic> chooseDataList = []; //选择的数据的map,回传回去
  List<int> chooseIdsList = []; //选择的数据的id,回传回去

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Log.d('selectedIds==${widget.selectedIds}' );
    if(widget.selectedIds!= null){
      chooseIdsList = widget.selectedIds!;
    }
    Log.d('selectedIds==${widget.selectedIds}' );
    getDataList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colour.white,
      appBar: AppBarWidget.withRightActions(
        widget.title,
      ),
      body: Column(
        children: [
          Container(
            height: 54,
            color: Colors.white,
            child: searchWidget(context),
          ),
          Container(
            color: Colour.backgroundColor,
            height: 10,
          ),
          Expanded(
            child: SmartRefresher(
                enablePullDown: true,
                controller: refreshController,
                onRefresh: onRefresh,
                header: ListTips.classicHeader,
                footer: ListTips.generateClassicFooter,
                child: dataList.isEmpty
                    ? ListEmptyWidget(topPosition: 82)
                    : ListView.builder(
                        padding: EdgeInsets.zero,
                        itemBuilder: (BuildContext context, int index) {
                          return _itemWidget(dataList[index]);
                        },
                        itemCount: dataList.length,
                      )),
          ),
        ],
      ),
      bottomNavigationBar: SafeArea(
        child: YtBrnBottomButtonPanel(
            enableMainButton: chooseIdsList.isNotEmpty,
            mainButtonName: ResKey.save.tr,
            mainButtonOnTap: () => save(),
            secondaryButtonName: ResKey.cancel.tr,
            enableSecondaryButton: true,
            secondaryButtonBorder: Border.all(color: Colour.dividerColor),
            secondaryButtonOnTap: () => Get.back()),
      ),
    );
  }

  getDataList({bool isShowLoading = true}) async {
    if (isShowLoading) showLoading(toast:ResKey.loading.tr);
    var params = widget.params;
    params?[widget.searchKey] = searchName;
    var result = await Configs.httpClient
        .get(widget.listUrl, queryParameters: params, onError: (error) {
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    List tempList = [];
      tempList = result??[];
      if(tempList.isNotEmpty){
        chooseDataList.clear();
        for (var element in tempList) {
            if(element[widget.keyId] != null && chooseIdsList.contains(element[widget.keyId])){
              element['isSelected'] = true;
              chooseDataList.add(element);
            }else{
              element['isSelected'] = false;
            }
        }
      }
      dataList = tempList;
      setState(() {});

  }

  onRefresh() {
    getDataList(isShowLoading: false);
  }

  save() {
    widget.selectedCompleted(chooseDataList,chooseIdsList);
    Get.back();
  }

  _itemWidget(Map map) {
    return SizedBox(
      // color: Colors.red,
      height: 50,
      child: Column(
        children: [
          Gaps.hGap16,
          Row(
            children: [
              Gaps.hGap16,
              Text(
                map[widget.showName].toString(),
                style: ytTextStyle(color: map['isSelected']?Colour.primaryColor:Colour.mainTextColor, fontSize: 16),
              ),
              const Spacer(),
              Container(
                padding: const EdgeInsets.only(right: 6),
                child: IconButton(
                  iconSize: 20,
                  icon: (map['isSelected'] != null && map['isSelected'] == true)
                      ? const Icon(
                          Icons.check_circle,
                          color: Colour.primaryColor,
                        )
                      : const Icon(
                          Icons.circle_outlined,
                          color: Colour.diabledButtoBgColor,
                        ),
                  onPressed: () {
                    if(widget.isMultiSelect){
                      if (map['isSelected'] != null &&
                          map['isSelected'] == true) {
                        map['isSelected'] = false;
                        chooseDataList
                            .removeWhere((element) => element[widget.keyId] == map[widget.keyId]);
                        chooseIdsList.remove(map[widget.keyId]);
                      } else {
                        map['isSelected'] = true;
                        chooseDataList.add(map);
                        chooseIdsList.add(map[widget.keyId]);
                      }
                    }else{
                      if(chooseIdsList.isNotEmpty && chooseIdsList.first.toString() == map[widget.keyId].toString()){
                        return;
                      }
                      for (var element in dataList) {
                        if(map[widget.keyId].toString() == element[widget.keyId].toString()){
                          element['isSelected'] = true;
                          chooseDataList.clear();
                          chooseIdsList.clear();
                          chooseDataList.add(element);
                          chooseIdsList.add(element[widget.keyId]);
                        }else {
                          element['isSelected'] = false;
                        }
                      }
                    }
                    Log.d('chooseDataList==$chooseDataList');
                    setState(() {});
                  },
                ),
              ),
            ],
          ),
          Container(
            color: Colour.dividerColor,
            margin: const EdgeInsets.only(left: 16, right: 16),
            height: 1,
          )
        ],
      ),
    );
  }

  Widget searchWidget(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: BrnSearchText(
            maxHeight: 40,
            hintStyle:
                TextStyles.styleWith(16.sp, color: const Color(0xFFCCCCCC)),
            textStyle: TextStyles.f16,
            hintText: widget.searchPlaceholder,
            outSideColor: Colors.transparent,
            innerColor: Colour.backgroundColor,
            borderRadius: BorderRadius.circular(6),
            innerPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0),
            onTextChange: DebounceUtils.debounceInput((p0) {
              // searchName = p0;
              // getDataList();
            }),
            onTextClear: () {
              searchName = '';
              getDataList();
              return false;
            },
            onTextCommit: (p0) {
              searchName = p0;
              getDataList();
            },
          ),
        ),
      ],
    );
  }
}
